package com.triple.triplerpc.loadbalancer;

import com.triple.triplerpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡器
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    /**
     * 当前轮询的下标
     * 使用 JUC 包的 AtomicInteger 实现原子计数器，防止并发冲突问题
     */
    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        System.out.println(" >>> 当前采用的负载均衡策略 - 轮询");
        if (serviceMetaInfoList.isEmpty()) {
            return null;
        }
        // 只有一个服务, 无需轮询
        int size = serviceMetaInfoList.size();
        if (size == 1) {
            return serviceMetaInfoList.get(0);
        }
        // 取模算法轮询
        int index = currentIndex.getAndIncrement() % size; // 获取currentIndex并增加1 然后对size取模
        return serviceMetaInfoList.get(index);
    }

}
